{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Here, we want to create mask-files\n",
    "# from the geojson-files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# GeoJSON --> .png"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plot and save the given coordinates in GeoJSON files."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "import json\n",
    "import geoio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ResimPATH = 'TRAINING TIF-FILE PATH/Train/AOI_2_Vegas_Train/RGB-PanSharpen' \n",
    "# All the pictures from the given path\n",
    "ResimAdlari = os.listdir(ResimPATH)\n",
    "\n",
    "GeoJSONPATH = 'TRAINING GEOJSON-FILE PATH/Train/AOI_2_Vegas_Train/geojson/buildings'\n",
    "# All the geojson-files from the given path\n",
    "GeoAdlari = os.listdir(GeoJSONPATH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# DosyaNumarasi takes the number from 0 to how big your training dataset\n",
    "for DosyaNumarasi in range(len(GeoAdlari)):\n",
    "\n",
    "    # data holds the info for the each GeoJSON-file\n",
    "    with open(GeoJSONPATH+'/'+GeoAdlari[DosyaNumarasi]) as f:\n",
    "        data = json.load(f)\n",
    "        \n",
    "    # RGBTIFResmi holds the info for each TIF-file\n",
    "    RGBTIFResmi = geoio.GeoImage(ResimPATH+'/'+ResimAdlari[DosyaNumarasi])\n",
    "\n",
    "    cokgenler = [] # Hold the coordinates for each building in the picture.\n",
    "                   # (Outside for loop is for each picture, and here, cokgenler\n",
    "                   # will hold the coordinates for each building in one picture.)\n",
    "    types = [] # Holds the type of the buldings (MultiPolygon - Partial Building - Point)\n",
    "               # We are not interested in the points.\n",
    "        \n",
    "    # Create the pane size of 650x650 to put the figures from geojson-file. Otherwise,\n",
    "    # the buildings may be flipped or they may saved one by one \n",
    "    arkaPlan = np.zeros([650,650])\n",
    "    plt.imshow(arkaPlan)\n",
    "\n",
    "    try:\n",
    "        # We do not know how many buildings the picture includes.\n",
    "        # So, we just give very big number to make sure that we utilized\n",
    "        # all the buildings in one picture.\n",
    "        # In short, bina keeps what order the building is.\n",
    "        for bina in range(2000):\n",
    "            tip = str(data['features'][bina]['geometry']['type'])\n",
    "            types.append(tip) # Append all the type of the buildings\n",
    "\n",
    "            # If type is point, do not do anything\n",
    "            if tip == ('Point'):\n",
    "                pass\n",
    "            \n",
    "            # If type is MultiPolygon, cokgenler will hold the coordinates\n",
    "            elif tip == ('MultiPolygon'):\n",
    "                kucukBinalar = (data['features'][bina]['geometry']['coordinates'])\n",
    "                for b in range(len(kucukBinalar)):        \n",
    "                    cokgenler.append(kucukBinalar[b])\n",
    "                    \n",
    "            # For the rest of the types, cokgenler will hold the coordinates again\n",
    "            else:\n",
    "                cokgenler.append(data['features'][bina]['geometry']['coordinates'])\n",
    "\n",
    "    except IndexError:\n",
    "        # If we utilized all the buildings in the given picture,\n",
    "        # lest create mask for each one.\n",
    "        \n",
    "        # cokgenBina holds the each building's coordinates\n",
    "        for cokgenBina in cokgenler:  \n",
    "\n",
    "            # binaNoktalari holds the individual edge coordinates for each building.\n",
    "            for binaNoktalari in cokgenBina:\n",
    "                \n",
    "                # To hold the edge coordinates (in pixel form)\n",
    "                doldurX = []\n",
    "                doldurY = []\n",
    "\n",
    "                # noktas holds x and y for each edge coordinate\n",
    "                for noktas in binaNoktalari:\n",
    "                    \n",
    "                    # Convert Latitude&Longitude to the pixels\n",
    "                    xPixel, yPixel = RGBTIFResmi.proj_to_raster(noktas[0], noktas[1])\n",
    "                    \n",
    "                    # The pixels may be 650 which defaces the masks.\n",
    "                    xPixel = 649 if xPixel > 649 else xPixel\n",
    "                    yPixel = 649 if yPixel > 649 else yPixel\n",
    "                    \n",
    "                    # Keep x and y in pixel form\n",
    "                    doldurX.append(xPixel)\n",
    "                    doldurY.append(yPixel)\n",
    "                    \n",
    "                # To paint between given pixel values\n",
    "                plt.fill_between(doldurX, doldurY, facecolor='red')\n",
    "                \n",
    "                # To remove white area around matplotlib figure\n",
    "                fig = plt.figure(1)\n",
    "                extent = plt.gca().get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n",
    "\n",
    "                # Adjust the DPI for 650x650\n",
    "                # and save the figure\n",
    "                # While saving, you should put them in order; 0 to ...\n",
    "                fig.savefig('Where to save the figure '+str(DosyaNumarasi)+'.png', bbox_inches=extent, dpi=215.24)\n",
    "            \n",
    "        # Close the figure after an image is done.\n",
    "        plt.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
